#include "socket_send_buff.h"

const size_t SocketSendBuff::HEADER_SIZE = 16;
const size_t SocketSendBuff::FIELD_SIZE  = 16;
const size_t SocketSendBuff::MAX_BODY_SIZE = 1024;

SocketSendBuff::SocketSendBuff(const char *header_, const char *body_): Buff() {
	header = new char[HEADER_SIZE+10];
	body = new char[MAX_BODY_SIZE+10];
	
	memset(header, 0, sizeof(char)*(HEADER_SIZE+10));
	memset(body, 0, sizeof(char)*(MAX_BODY_SIZE+10));
	
	strncpy(header, header_, HEADER_SIZE);
	strcpy(body, body_);
	
	printf("SocketSendBuff: %s\n", header);

	body_length = 0;
	status = 0;
	index = 0;
	remain = HEADER_SIZE;
}

SocketSendBuff::~SocketSendBuff() {
	delete[] header;
	delete[] body;
}

ssize_t SocketSendBuff::send_header(int fd) {
	ssize_t tot = 0;
	while (remain > 0) {
		ssize_t n = write(fd, header + index, remain);
		if (n == -1) return n;
		tot += n;
		index += n;
		remain -= n;
	}
	status = 1;
	return tot;
}

ssize_t SocketSendBuff::send_body(int fd) {
	ssize_t tot = 0;
	while (remain > 0) {
		ssize_t n = write(fd, body+index, remain);
		if (n == -1) return n;
		tot += n;
		index += n;
		remain -= n;
	}
	status = 2;
	return tot;
}

void SocketSendBuff::get_body_length() {
	body_length = strlen(body);
	index = 0;
	remain = body_length;
}

bool SocketSendBuff::finish_header() {
	return status >= 1; 
}

bool SocketSendBuff::finish_body() {
	return status >= 2;
}
